//
//  CoreDataUtility.m
//  Ubiqus
//
//  Created by Le Quang Vinh on 12/11/12.
//  Copyright (c) 2012 Le Quang Vinh. All rights reserved.
//

#import "CoreDataUtility.h"

@implementation CoreDataUtility
@synthesize managedObjectModel = _managedObjectModel;
@synthesize managedObjectContext    = _managedObjectContext;
@synthesize persistentStoreCoordinator  = _persistentStoreCoordinator;


/****************************************************************************
 ID:			defaultDataManager
 Func:			
 In:			void
 Out:			void
 IO:			void
 Return:		Singleton of DataManager
 Date:			
 Creator:		
 ****************************************************************************/
static CoreDataUtility  *sharedObject = nil;
+ (CoreDataUtility*)defaultCoredataUtility{
    if (sharedObject == nil) {
        @synchronized(self){
            if (sharedObject == nil) {
                sharedObject = [[CoreDataUtility alloc] init];
            }
        }
    }
    return sharedObject;
}

/****************************************************************************
 ID:            dealloc 
 Func:          Destructor of class
 In:            none
 Out:           none
 IO:            void
 Return:		void
 Date:			2012.03.18
 Creator:		4G Secure Team DD
 ****************************************************************************/
- (void)dealloc{
    [super dealloc];
    [_managedObjectContext release];
    [_managedObjectContext release];
    [_persistentStoreCoordinator release];
}


/****************************************************************************
 ID:			applicationDocumentDirectory
 Func:			The path point to application directory
 In:			void
 Out:			void
 IO:			void
 Return:		NSURL
 Date:			2012.03.18
 Creator:		4G Secure Team DD
 ****************************************************************************/
- (NSURL*)applicationDocumentDirectory{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

/****************************************************************************
 ID:                saveContext
 Func:              Save current context
 In:                none
 Out:               none
 IO:                none
 Return:            void
 Date:              2012.03.18
 Creator:           4G Secure Team DD
 ****************************************************************************/

- (void)saveContext{
    NSError* error = nil;
    NSManagedObjectContext* context = self.managedObjectContext;
    if (context != nil) {
        if ([context hasChanges] && ![context save:&error]) {
            NSLog(@"Unresolved error %@, %@",error, [error userInfo]);
            abort();
        }
    }
}

#pragma mark - Core Data Stack
/****************************************************************************
 ID:            managedObjectContext
 Func:			Accessory of managed object context
 In:			none
 Out:			none
 IO:			none
 Return:		(NSManagedObjectContext*)
 Date:			2012.03.18
 Creator:		4G Secure Team DD
 ****************************************************************************/

- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

/****************************************************************************
 ID:		managedObjectModel	
 Func:		Accessory of object model, get from data model file	
 In:		none	
 Out:		none	
 IO:		none	
 Return:	(NSManagerObjectModel*)	
 Date:		2012.03.18	
 Creator:	4G Secure Team DD	
 ****************************************************************************/
- (NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"LeanDataModel" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

/****************************************************************************
 ID:			persistentStoreCoordinator
 Func:			The persistent store coordinator for the application
 In:			none
 Out:			none
 IO:			none
 Return:		(NSPersistentStoreCoordinator*)
 Date:			2102.03.18
 Creator:		4G Secure Team DD
 ****************************************************************************/
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"LeanDataModel.sqlite"];
    
    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        /*
         Replace this implementation with code to handle the error appropriately.
         
         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
         
         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.
         
         
         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
         
         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
         
         * Performing automatic lightweight migration by passing the following dictionary as the options parameter:
         @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}
         
         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
         
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


/****************************************************************************
 ID:		getObjectsForEntity
 Func:		Search objects for an specfially entity with predicate, sortkey, ascending
 In:		none
 Out:		none
 IO:		none
 Return:	NSURL
 Date:		2012.03.18
 Creator:	4G Secure Team DD
 ****************************************************************************/
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

#pragma mark - Base funciton for Data manager
/****************************************************************************
 ID:		getObjectsForEntity	
 Func:		Search objects for an specfially entity with predicate, sortkey, ascending
 In:		+(NSString*)entityName: entity's name
            +(NSString*)sortKey:    key for sorting
            +(BOOL)sortAscending:   sort ascending
            +(NSPredicate*)predicate: predicate for search
            +(NSManagedObjectContext*)context: --
 Out:		none	
 IO:		none	
 Return:	(NSMutableArray*)	
 Date:		2012.03.18	
 Creator:	4G Secure Team DD	
 ****************************************************************************/

- (NSMutableArray*)searchObjectsForEntity:(NSString *)entityName withSortKey:(NSString *)sortKey andSortAscending:(BOOL)sortAscending andPredicate:(NSPredicate*)predicate andContext:(NSManagedObjectContext *)context{
    NSFetchRequest* fetchRequest = [[NSFetchRequest alloc] init];
    
    NSEntityDescription* entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
        
    if (predicate != nil) {
        [fetchRequest setPredicate:predicate];
    }
    
    if (sortKey != nil) {
        NSSortDescriptor* sortDescript = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:sortAscending];
        [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDescript]];
        [sortDescript release];
    }

    
    NSError* error = nil;
    NSMutableArray* result = [[[context executeFetchRequest:fetchRequest error:&error] mutableCopy] autorelease];
    if (result == nil) {
        NSLog(@"executeFetchRequest error %@,%@",error,[error userInfo]);
        return nil;
    }
    [fetchRequest release];
    return  result;
}

/****************************************************************************
 ID:			getObjectsForEntity
 Func:			Get all object for an entity
 In:			+(NSString*)entityName: entity's name
                +(NSString*)sortKey:    key for sorting
                +(BOOL)sortAscending:   sort ascending
                +(NSManagedObjectContext*)context: --
 Out:			none
 IO:			none
 Return:		(NSMutableArray*)
 Date:			2012.03.18
 Creator:		4G Secure Team DD
 ****************************************************************************/
- (NSMutableArray*)getObjectsForEntity:(NSString *)entityName withSortKey:(NSString *)sortKey andSortAscending:(BOOL)sortAscending andContext:(NSManagedObjectContext *)context{
    return [self searchObjectsForEntity:entityName withSortKey:sortKey andSortAscending:sortAscending andPredicate:nil andContext:context];
}



/****************************************************************************
 ID:			createNewObjectForEntityName
 Func:			Create an new object for an entity name
 In:			+(NSString*)entityName
 Out:			none
 IO:			none
 Return:		(NSManagedObject*)
 Date:			2012.03.19
 Creator:		4G Secure Team DD
 ****************************************************************************/
- (NSManagedObject*)createNewObjectForEntityName:(NSString *)entityName{
    CoreDataUtility* dataManager = [CoreDataUtility defaultCoredataUtility];
    NSManagedObject* object = [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:dataManager.managedObjectContext];
    return object;
}



@end
